//
//  YHHomeViewController.swift
//  YHWeibo
//
//  Created by yuhao.mac on 16/6/23.
//  Copyright © 2016年 yuhao.mac. All rights reserved.
//

import UIKit

//定义cell重用标示
private let statusCellId = "statusCellId"

class YHHomeViewController: YHVisitorViewController {
    
    //定义一个保存微博数据的数组
    var statusArray:[YUStatus] = [YUStatus]()
    
    let refresh = YHRefresh()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        if !isLogin{
            visitorView?.setupVisitorView(nil, title: nil)
            return
        }
        
        //设置tableView相关
        setTableViewInfo()
        
        
        //请求微博首页数据
        loadStatusData(activityView.isAnimating())
        
        tableView.tableFooterView = activityView
        
    }
    
    func setTableViewInfo(){
        //注册cell
        tableView.registerClass(YHStatusCell.self, forCellReuseIdentifier: statusCellId)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        //设置分隔线显示风格
        tableView.separatorStyle = .None
        
        refresh.addTarget(self, action: "refreshAction", forControlEvents: .ValueChanged)
        tableView.addSubview(refresh)
    }
    
    @objc private func refreshAction(){
        
         loadStatusData(activityView.isAnimating())
    }
    
    //懒加载控件
    private lazy var activityView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = ThemeColor
        return view
    }()
}

extension YHHomeViewController {

    func loadStatusData(pullUp:Bool){
        
        var sinceId:Int64 = 0
        var maxId:Int64 = 0
        
        //上拉加载更多
        if pullUp{
            maxId = statusArray.last?.id ?? 0
            if maxId > 0{
                maxId -= 1
            }
        }else{
            //下拉刷新
            sinceId = statusArray.first?.id ?? 0
        }
        YHNetworkTools.sharedTools.homeLoadStatusData(sinceId, maxId: maxId, success: { (response) -> () in
            
            self.endRefreshing()
            
            //判断我们请求回来的数据是否有值，是否是一个数组
            guard let res = response?["statuses"] as? [[String:AnyObject]] else{
                print("返回数据为nil或者类型不对")
                return
            }
            
            //定义了一个临时数组存放模型数据
            var tempArr:[YUStatus] = [YUStatus]()
            //遍历数组，完成字典转模型
            for dic in res{
                let status = YUStatus(dict: dic)
                
                tempArr.append(status)
            }
            
            //上拉加载更多
            if pullUp{
                self.statusArray = self.statusArray + tempArr
            }else{
                self.statusArray = tempArr + self.statusArray
            }
            
            self.tableView.reloadData()
            
            
            }) { (error) -> () in
                print("失败了\(error)")
        }
    }
    func endRefreshing(){
        self.activityView.stopAnimating()
        self.refresh.endRefreshing()
    }
}

extension YHHomeViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier(statusCellId, forIndexPath: indexPath) as! YHStatusCell
        
        cell.status = statusArray[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if statusArray.count == indexPath.row + 1 && !activityView.isAnimating(){
            activityView.startAnimating()
            //请求数据 
            loadStatusData(activityView.isAnimating())
        }
        
    }
}






